<?php
namespace app\api\controller;
use think\facade\Db;
use think\facade\Env;
use hg\apidoc\annotation as Apidoc;


/**
 * @Apidoc\Title("PC端微信扫码登录")
 */
class PcOauth extends ApiBase
{

    private $app_id; //微信开放平台appid
    private $app_secret; //微信平台秘钥

    public function __construct() {
        parent::__construct();
        $this->app_id     = app()->env->get('open_app_id'); // 小程序 app_id
        $this->app_secret = app()->env->get('open_app_secret'); // 小程序 app_secret
    }

    /**
     * @Apidoc\Title("PC端微信扫码登录")
     * @Apidoc\Desc("PC端微信扫码登录")
     * @Apidoc\Url("/api/pc_login")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("js_code", type="string",require=true, desc="code值")
     * @Apidoc\Returned("user", type="strinng", desc="用户信息")
     */
  public function oauth_login() {
        try {
            $js_code    = urldecode(param_check('js_code')); // 小程序wx.login获取的code, 必填参数
            $app_id     = $this->app_id; // 小程序 app_id
            $app_secret = $this->app_secret; // 小程序 app_secret
            // 请求微信授权接口, 获取token, unionid, openid
            $url  = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$js_code}&grant_type=authorization_code";
            $data = json_decode(curl('GET', $url), true);
            // 判断接口是否请求成功
            if(empty($data['access_token'])) {
                json_response(0, $data['errmsg'], $data);
            }
            $token = $data['access_token'];
            $unionid = $data['unionid'];
            //根据token，unionid获取用户头像昵称
            $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid={$unionid}";
            $data = json_decode(curl('GET', $url), true);
            // 判断接口是否请求成功
            if(empty($data['openid'])) {
                json_response($data['errcode'], $data['errmsg'], $data);
            }
            $user['nickname'] = $data['nickname'];
            $user['avatar'] = $data['headimgurl'];
            json_response(1, 'success', [
                'user' => $user
            ]);
        } catch (\Exception $e) {
            json_response(0, '接口错误', [
                'info' => $e->getMessage(),
                'line' => $e->getLine()
            ]);
        }
    }
}